#include <stdint.h>
#include "../libc/function.h"
#include "../libc/string.h"
#include "port.h"
#include "../driver/screen.h"
#include "../kernel/task.h"
#include "timer.h"

uint32_t tick = 0;

static uint32_t timer_callback(isr_registers_t *reg) {
    tick++;

    // 任务调度
    if(tick % 50 == 0) {
        task_t *task = schedule_task(reg);
        // char str[50];
        // int2ascii((int)task, str);
        // kprint(str);
        // kprint("\n");
        if(task)
            return *(uint32_t *)task;
    }
    

    // char str[20];
    // if(tick % 50 == 0) {
    //     int2ascii(tick/50, str);
    //     kprint("tick: ");
    //     kprint(str);
    //     kprint("\n");
    // }
    return (uint32_t)reg;
}


void init_timer(int freq) {
    isr_handler_register(IRQ0, timer_callback);
    int divisor = 1193180 / freq;
    uint8_t divisor_low = (uint8_t) (divisor & 0xff);
    uint8_t divisor_high = (uint8_t) ((divisor >> 8) & 0xff);
    port_byte_out(0x43, 0x36);
    port_byte_out(0x40, divisor_low);
    port_byte_out(0x40, divisor_high);
}
